<template>
	<view class="category-level">
		<view class="category-level-box" v-if="cateList.length && isLoadingCate">
			<nsSearch></nsSearch>
			<view class="category-goods">
				<scroll-view scroll-y="true" class="oneScroll">
					<view class="oneScroll-item using-hidden" v-for="(item, index) in cateList" :key="index" :class="{ 'active color-base-bg-before': item.category_id == oneIndex }"
					 @click="selectOneCategory(index,item.category_id)">
						{{ item.short_name ? item.short_name : item.category_name }}
					</view>
				</scroll-view>
				<view class="twoScroll">
					<view class="category-cate-top"></view>
					<template v-show="!isLoading">
						<scroll-view scroll-y="true" :style="{ height: 'calc(100% - ' + height + ' )' }" @scrolltolower="getGoodsList( oneIndex )">
							<image class="cate-adv" v-if="cateList[treeIndex].image_adv" @error="cateList[treeIndex].image_adv = $util.img('/upload/uniapp/default_ad.png')"
							 :src="$util.img(cateList[treeIndex].image_adv)" mode="widthFix"></image>
							<view v-for="(item, index) in goodsList" :key="index">
								<view class="twoScroll-item-box" @click="toDetail(item.sku_id)">
									<image class="twoScroll-item-image" :src="$util.img(item.sku_image, { size: 'mid' })" @error="goodsImageError(index)"
									 mode="aspectFill" />
									<view class="goods_detail">
										<view class="goods_name multi-hidden">{{ item.goods_name }}</view>
										<view class="goods-label" v-if="goodsTag(item) != ''">{{ goodsTag(item) }}</view>
										<view class="goods-sale">
											<text class="color-tip">累计 {{item.sale_num}} 份</text>
											<text class="split"></text>
											<text class="color-base-text" v-if="item.stock > 30">剩余 {{item.stock}} 份</text>
											<text class="color-base-text" v-else>仅剩 {{item.stock}} 份</text>
										</view>
										<view class="goods_price">
											<view class="goods-price-box">
												<view class="member-price-tag member-price-tag-vip-1" v-if="item.member_price && item.member_price == showPrice(item)">
													<image :src="$util.img('upload/uniapp/index/vip_1.png')" mode="widthFix"></image>
													<text>会员价</text>
												</view>
												<view class="member-price-tag member-price-tag-vip-2" v-else-if="item.promotion_type == 1">
													<image :src="$util.img('upload/uniapp/index/vip_2.png')" mode="widthFix"></image>
													<text>折扣价</text>
												</view>

												<text class="sale-price">
													<text class="unit font-size-tag">￥</text>
													<text class="price">{{ showPrice(item).split('.')[0] }} <text class="fs-32">.{{ showPrice(item).split('.')[1] }}</text>
													</text>
												</text>
											</view>

											<text class="line-price">
												<text class="price-icon">￥</text>
												{{ item.market_price > 0 ? item.market_price : item.price }}
											</text>

											<view class="info-wrap">
												<!-- <button class="info-btn color-base-bg" v-if="item.goods_spec_format" @click.stop="getGoodsSkuDetail(item.sku_id)">加入购物车</button>
												<button class="info-btn color-base-bg" v-else="(!item.goods_spec_format && item.num <= 0 && token) || !token" @click.stop="cartNumChange('add', item)">加入购物车</button>
												<view class="careBox" v-if="!item.goods_spec_format && item.is_virtual == 0 && item.num > 0">
													<text class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item)"></text>
													<input :value="item.num" readonly disabled="disabled" unselectable="on" />
													<text class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item)"></text>
												</view> -->

												<!-- <text v-if="item.goods_spec_format" @click.stop="getGoodsSkuDetail(item.sku_id)" class="color-base-bg">加入购物车</text>
												<block v-else>
													<text v-if="item.num > 0" class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item)"></text>
													<input v-if="item.num > 0" :value="item.num" readonly disabled="disabled" unselectable="on" />
													<text class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item)"></text>
												</block> -->
											</view>
										</view>

										<view class="careBox" v-if="item.goods_spec_format">
											<button class="info-btn color-base-bg" @click.stop="getGoodsSkuDetail(item.sku_id)">选规格</button>
											<view v-if="item.num" class="tag-num">{{item.num}}</view>
										</view>

										<view class="careBox" v-if="!item.goods_spec_format">
											<button v-if="item.num <= 0 || !token" class="info-btn color-base-bg" @click.stop="cartNumChange('add', item)">加入购物车</button>
											<text v-if="item.num > 0" class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item)"></text>
											<input v-if="item.num > 0" :value="item.num" readonly disabled="disabled" unselectable="on" />
											<text v-if="item.num > 0" class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item)"></text>
										</view>
									</view>
								</view>
							</view>

							<!-- 加载中 -->
							<view class="mescroll-upwarp" v-show="false">
								<ns-loading></ns-loading>
							</view>
							<ns-empty v-if="is_getMore && goodsList.length == 0" :isIndex="!1" :fixed="!1" text="该分类下暂无商品"></ns-empty>
						</scroll-view>
					</template>
				</view>
			</view>
		</view>
		<ns-empty :isIndex="!1" v-else></ns-empty>

		<!-- 加载中 -->
		<view class="mescroll-upwarp" v-show="!isLoadingCate">
			<ns-loading></ns-loading>
		</view>
		<ns-goods-sku-category @getCartData="getCartData" ref="goodSkuNew" @refresh="refreshGoodsSkuDetail"></ns-goods-sku-category>

		<ns-login ref="login"></ns-login>
	</view>
</template>

<script>
	import nsGoodsSkuCategory from '@/components/ns-goods-sku/ns-goods-sku-category.vue';
	import nsLoading from '@/components/ns-loading/ns-loading.vue';
	import nsSearch from '@/components/ns-search/ns-search.vue';
	import globalConfig from '@/common/js/golbalConfig.js';
	import category from '@/components/diy-goods-category/diy-goods-category.js';
	export default {
		components: {
			nsLoading,
			nsGoodsSkuCategory,
			nsSearch
		},
		props: {
			value: {
				type: Object,
				default: () => {
					return {};
				}
			},
			is_padd_bom: {
				type: Boolean,
				default: false
			},
			category_id: {
				type: String,
				default: false
			}
		},
		data() {
			return {
				height: '',
				oneIndex: 0,
				cartList: [], //购物车
				cateList: [], //分类
				oneCategoryId: 0, //当前分类菜单的id
				categoryAdvImage: '',
				currentRoute: '',
				token: '',
				treeIndex: 0,
				page_num: 1,
				is_getMore: false,
				isNetwork: 1
			};
		},
		mixins: [category, globalConfig],
		onLoad() {
			this.page_num = 1;
			this.is_getMore = false;
			this.getCategoryList()
		},
		computed: {
			flRefresh() {
				return this.$store.state.flRefresh;
			},
			getcategoryid() {
				return this.category_id
			},
			tokenStore() {
				return this.$store.state.tokenStore;
			},
		},
		watch: {
			flRefresh: function(nval, oval) {
				if (nval == 1) {
					this.page_num = 1;
					this.is_getMore = false;
					this.getCategoryList();
				}
			},
			getcategoryid: function(nval, oval) {
				if (nval != 0) {
					this.goodsList = [];
					this.page_num = 1;
					this.is_getMore = false;
					this.oneIndex = nval;
					this.getCategoryList();
				}
			},
			tokenStore(val, old) {
				this.token = val;
				this.page_num = 1;
				this.is_getMore = false;
				this.getCategoryList();
			}
		},
		created() {
			if (this.category_id != 0) {
				this.oneIndex = this.category_id;
			}
			let currentPage = getCurrentPages()[getCurrentPages().length - 1];
			this.currentRoute = '/' + currentPage.route;
			this.token = uni.getStorageSync('token');
			this.page_num = 1;
			this.is_getMore = false;
			this.getCategoryList();
		},
		methods: {
			getCategoryList() {
				this.isLoadingCate = false;
				this.$api.sendRequest({
					url: '/api/goodscategory/tree',
					data: {
						level: this.value.level,
						template: this.value.template
					},
					success: res => {
						this.isLoadingCate = true;
						if (res.code != 0) {
							this.$util.showToast({
								title: res.message
							});
							return false;
						}
						if (res.code == 0 && res.data.length) {
							this.cateList = res.data;
							// if(!this.oneIndex){ 
								if(this.page_num == 1) this.is_getMore = false;
								this.oneIndex = this.category_id
								this.getGoodsList( this.category_id );
							// } else {
								// this.getGoodsList();
							// }

							this.$nextTick(function() {
								const query = uni.createSelectorQuery().in(this);
								query
									.select('.category-cate-top')
									.boundingClientRect(data => {
										this.height = parseInt(data.height) + 'px';
									})
									.exec();
							});
						}
						this.$emit('netFinish', true);
					}
				});
			},
			showPrice(data) {
				let price = data.discount_price;
				if (data.member_price && data.member_price < price) price = data.member_price;
				return price;
			},
			getGoodsList(e) {
				if (!this.isNetwork || this.is_getMore) return;

				this.isNetwork = 0;
				this.isLoading = true;

				this.$api.sendRequest({
					url: '/api/goodssku/page',
					data: {
						page: this.page_num,
						page_size: 10,
						category_id: e || this.oneIndex 
					},
					success: res => {
						this.isNetwork = 1;
						this.isLoading = false;

						if (res.code == 0 && res.data) {
							let newArr = res.data.list.length ? res.data.list : [];

							for (let i in newArr) {
								newArr[i]['sku_image'] = newArr[i]['goods_image'].split(',')[0];

							}

							//设置列表数据
							if (this.page_num == 1) this.goodsList = []; //如果是第一页需手动制空列表
							this.goodsList = this.goodsList.concat(newArr); //追加新数1据
							
							// if (e == this.oneIndex) {
							// 
							if(res.data.page_count > this.page_num){
								++this.page_num;
							}
							// }
							
							this.getCartData();
							this.$store.commit('setflRefresh', '0');
							if (this.goodsList.length == res.data.count) this.is_getMore = true;

						}

						this.$emit('netFinish', true);
					}
				});
			},
			getCartData() {
				if (!uni.getStorageSync('token')) {
					for (let goods_index in this.goodsList) {
						let goods_item = this.goodsList[goods_index];
						goods_item.num = 0;
					}
					this.$forceUpdate();
					this.$emit('netFinish', true);
					return;
				}

				this.$api.sendRequest({
					url: '/api/cart/lists',
					success: res => {
						if (res.code >= 0) {
							this.cartList = res.data;

							for (let goods_index in this.goodsList) {
								let goods_item = this.goodsList[goods_index],
									sku_id = goods_item.sku_id,
									goods_id = goods_item.goods_id,
									num = 0,
									cart_id = '';

								for (let cart_index in this.cartList) {
									let cart_item = this.cartList[cart_index];
									if (goods_id == cart_item.goods_id && cart_item.activity_type == '') {
										num += cart_item.num;
										cart_id = cart_item.cart_id;
									}
								}
								goods_item.num = num;
								goods_item.cart_id = cart_id;

								if (typeof goods_item.num === 'undefined' || goods_item.num === null) {
									goods_item.num = 0;
								}
							}
							this.$forceUpdate();
							this.$emit('netFinish', true);
						}
					}
				});
			},
			selectOneCategory(index, selectId) {
				this.oneIndex = selectId;
				this.treeIndex = index
				
				this.page_num = 1;
				this.is_getMore = false;
				this.isNetwork = true;
				this.goodsList = [];
				this.getGoodsList(selectId);

				this.$nextTick(function() {
					const query = uni.createSelectorQuery().in(this);
					query
						.select('.category-cate-top')
						.boundingClientRect(data => {
							this.height = data.height + 'px';
						})
						.exec();
				});
			}
		}
	};
</script>
<style lang="scss">
	@import '@/components/diy-goods-category/diy-goods-category.scss';

	/* 上拉加载区域 */
	.mescroll-upwarp {
		margin-top: 35vh;
	}
</style>
<style scoped>
	/deep/ .reward-popup .uni-popup__wrapper-box {
		background: none !important;
		max-width: unset !important;
		max-height: unset !important;
	}

	/deep/ .uni-input-input {
		font-size: 36rpx;
		font-family: Roboto;
		font-weight: bold;
		color: #303133;
	}

	.tag-num {
		display: block;
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		background: #FF1919;
		text-align: center;
		color: #fff;
		border-radius: 50%;
		position: absolute;
		top: -20rpx;
		right: 20rpx;
		font-size: 24rpx;
	}

	.h40 {
		height: 30rpx;
	}

	.mt-40 {
		margin-top: 20rpx;
		line-height: 1;
	}

	.shops-stock {
		font-size: 22rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #909399;
		padding-right: 10rpx;
	}

	.shops-sale-num {
		font-size: 22rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #FF6706;
		padding-left: 10rpx;
	}
</style>
